// TaskDashboardServiceImpl.java
package com.example.demo.service.impl;

import com.example.demo.controller.TaskDashboardVO;
import com.example.demo.controller.TaskHeatVO;
import com.example.demo.entity.Course;
import com.example.demo.entity.Task;
import com.example.demo.entity.TaskStatistics;
import com.example.demo.mapper.CourseMapper;
import com.example.demo.mapper.TaskMapper;
import com.example.demo.mapper.TaskStatisticsMapper;
import com.example.demo.service.TaskDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class TaskDashboardServiceImpl implements TaskDashboardService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskStatisticsMapper statisticsMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public TaskDashboardVO getTaskDashboard(String courseId) {
        TaskDashboardVO dashboard = new TaskDashboardVO();
        dashboard.setCourseId(courseId);

        // 获取课程名称
        Course course = courseMapper.selectCourseById(courseId);
        if (course == null) {
            throw new RuntimeException("课程不存在: " + courseId);
        }
        dashboard.setCourseName(course.getCourseName());

        // 获取所有任务
        List<Task> tasks = taskMapper.findByCourseId(courseId);
        if (tasks.isEmpty()) {
            dashboard.setTaskItems(new ArrayList<>());
            return dashboard;
        }

        // 获取所有任务统计
        List<TaskStatistics> statisticsList = statisticsMapper.findByCourseId(courseId);
        Map<Long, TaskStatistics> statMap = statisticsList.stream()
                .collect(Collectors.toMap(TaskStatistics::getTaskId, s -> s));

        // 组装任务项
        List<TaskDashboardVO.TaskItemVO> taskItems = tasks.stream().map(task -> {
            TaskDashboardVO.TaskItemVO item = new TaskDashboardVO.TaskItemVO();
            item.setTaskId(task.getTaskId());
            item.setTaskName(task.getTaskName());
            item.setCoreRequirements(task.getCoreRequirements());
            item.setDeadline(task.getDeadline());

            // 设置统计数据
            TaskStatistics stat = statMap.get(task.getTaskId());
            if (stat != null) {
                item.setViewCount(stat.getViewCount());
                item.setDiscussionCount(stat.getDiscussionCount());
                // 计算提交率
                if (stat.getTotalStudents() > 0) {
                    double rate = (double) stat.getSubmitCount() / stat.getTotalStudents() * 100;
                    item.setSubmissionRate(Math.round(rate * 100.0) / 100.0);
                } else {
                    item.setSubmissionRate(0.0);
                }
            }
            return item;
        }).collect(Collectors.toList());

        dashboard.setTaskItems(taskItems);
        return dashboard;
    }

    @Override
    public TaskHeatVO getTaskHeatDashboard(String courseId) {
        TaskHeatVO heatVO = new TaskHeatVO();
        heatVO.setCourseId(courseId);

        // 获取任务ID与名称的映射
        List<Task> tasks = taskMapper.findByCourseId(courseId);
        Map<Long, String> taskNameMap = tasks.stream()
                .collect(Collectors.toMap(Task::getTaskId, Task::getTaskName));

        // 处理查看热度
        List<TaskStatistics> viewStats = statisticsMapper.findByCourseIdOrderByViewCount(courseId);
        heatVO.setViewHeatList(buildHeatItems(viewStats, taskNameMap));

        // 处理讨论热度
        List<TaskStatistics> discussionStats = statisticsMapper.findByCourseIdOrderByDiscussionCount(courseId);
        heatVO.setDiscussionHeatList(buildHeatItems(discussionStats, taskNameMap));

        return heatVO;
    }

    private List<TaskHeatVO.HeatItemVO> buildHeatItems(List<TaskStatistics> stats, Map<Long, String> taskNameMap) {
        List<TaskHeatVO.HeatItemVO> items = new ArrayList<>();
        for (int i = 0; i < stats.size(); i++) {
            TaskStatistics stat = stats.get(i);
            TaskHeatVO.HeatItemVO item = new TaskHeatVO.HeatItemVO();
            item.setTaskId(stat.getTaskId());
            item.setTaskName(taskNameMap.getOrDefault(stat.getTaskId(), "未知任务"));
            item.setRank(i + 1);
            item.setCount(stat.getViewCount() != null ? stat.getViewCount() : stat.getDiscussionCount());
            items.add(item);
        }
        return items;
    }
}